﻿using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using Model.Other;
using Shop.Interface.Jwt;
using Shop.Models.Dto.User;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace Shop.Services.Jwt
{
    public class CustomJWTService : ICustomJWTService
    {
        private readonly JWTTokenOptions tokenOptions;
        public CustomJWTService(IOptionsMonitor<JWTTokenOptions> options) 
        {
            tokenOptions = options.CurrentValue;
        }
        public async Task<string> GetToken(UserRes user)
        {
            var result = await Task.Run(() => 
            {
                var claims = new[]
               {	
                    //把这些加到token里面
                    new Claim("Id",user.Id),
                    new Claim("NickName",user.NickName),
                    new Claim("Name",user.Name),
                    new Claim("UserType",user.UserType.ToString()),
                    new Claim("Image",user.Image==null?"":user.Image
                    ),
                };
                SymmetricSecurityKey key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(tokenOptions.SecurityKey));

                SigningCredentials creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);//生成票据

                //Nuget引入：System.IdentityModel.Tokens.Jwt
                JwtSecurityToken token = new JwtSecurityToken(
                 issuer: tokenOptions.Issuer,
                 audience: tokenOptions.Audience,
                 claims: claims,
                 expires: DateTime.Now.AddDays(1),
                 notBefore: null,
                 signingCredentials: creds);

                string res = new JwtSecurityTokenHandler().WriteToken(token);
                return res;
            });
            return result;
        }
    }
}
